﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VERKProjectHopur16.Models;
using System.Web.Security;
using VERKProjectHopur16.Helpers;

namespace VERKProjectHopur16.Controllers
{
    /// <summary>
    /// All functionality for administrators is in this controller
    /// </summary>
    [Authorize(Roles = "Administrators")]
    public class AdminController : ParentController
    {
        DataRepository m_rep = new DataRepository();

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult CreateContent(int? id)
        {
            if (id.HasValue )
            {
                int realID = id.Value;
                ContentViewModel model = new ContentViewModel();
                model.CategoryID = realID.ToString();
                return View(model);
            }
            return View("NotFound");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult CreateContent(ContentViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Content item = new Content();
                item.ContentID = model.ContentID;
                item.InsertDate = DateTime.Now;
                item.Title = model.Title;
                item.Text = model.Text;
                item.Active = true;

                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                item.CreatorID = UserID;
                item.DepartmentID = Convert.ToInt32(model.DepartmentID);
                item.CategoryID = Convert.ToInt32(model.CategoryID);
                item.AuthorID = Convert.ToInt32(model.AuthorID);
                item.LanguageID = Convert.ToInt32(model.LanguageID);
                m_rep.AddContent(item);

                switch (item.CategoryID)
                {
                    case 1:
                        return RedirectToAction("AllNews");
                    case 2:
                        return RedirectToAction("AllArticles");
                    case 3:
                        return RedirectToAction("AllRR");
                    case 4:
                        return RedirectToAction("AllPapers");
                    case 5:
                        return RedirectToAction("AllResearches");
                    default:    
                        return RedirectToAction("Index");
                }                              
            }
            else
            {
                return View(model);
            }
        }

        [HttpGet]
        public ActionResult EditContent(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                var model = m_rep.GetContentById(realID);

                if ( model == null )
                {
                    return View("NotFound");
                }

                ContentViewModel item = new ContentViewModel();
                item.ContentID = realID;
                item.Title = model.Title;
                item.Text = model.Text;
                item.DepartmentID = model.DepartmentID.ToString();
                item.CategoryID = model.CategoryID.ToString();
                item.AuthorID = model.AuthorID.ToString();
                item.LanguageID = model.LanguageID.ToString();
                return View(item);
            }
            else
            {
                return View("NotFound");
            }
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult EditContent(ContentViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Content item = new Content();
                item.ContentID = model.ContentID;
                item.Title = model.Title;
                item.Text = model.Text;
                item.Active = true;

                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                item.CreatorID = UserID;

                item.DepartmentID = Convert.ToInt32(model.DepartmentID);
                item.CategoryID = Convert.ToInt32(model.CategoryID);
                item.AuthorID = Convert.ToInt32(model.AuthorID);
                item.LanguageID = Convert.ToInt32(model.LanguageID);
                m_rep.UpdateContent(item);

                switch (item.CategoryID)
                {
                    case 1:
                        return RedirectToAction("AllNews");
                    case 2:
                        return RedirectToAction("AllArticles");
                    case 3:
                        return RedirectToAction("AllRR");
                    case 4:
                        return RedirectToAction("AllPapers");
                    case 5:
                        return RedirectToAction("AllResearches");
                    default:
                        return RedirectToAction("Index");
                }    
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult RemoveContent(int id)
        {
            var model = (from content in m_rep.GetAllContent()
                         where content.ContentID == id
                         && content.Active == true
                         select content).SingleOrDefault();           
            if ( model == null )
            {
                return View("NotFound");
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult RemoveContent(int? id)
        {
            if ( id.HasValue )
            {
                var model = (from content in m_rep.GetAllContent()
                             where content.ContentID == id
                             && content.Active == true
                             select content).SingleOrDefault();
                if ( model == null )
                {
                    return View("NotFound");
                }
                m_rep.DeleteContent(model);
                switch (model.CategoryID)
                {
                    case 1:
                        return RedirectToAction("AllNews");
                    case 2:
                        return RedirectToAction("AllArticles");
                    case 3:
                        return RedirectToAction("AllRR");
                    case 4:
                        return RedirectToAction("AllPapers");
                    case 5:
                        return RedirectToAction("AllResearches");
                    default:
                        return RedirectToAction("Index");
                }    
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult AllNews()
        {
            IEnumerable<Content> model;
            String strSort = "InsertDate";

            if (Session["orderNewsAdmin"] != null)
            {
                if (Session["orderNewsAdmin"].Equals(1))
                {
                    strSort = "Title";
                }
                else if (Session["orderNewsAdmin"].Equals(2))
                {
                    strSort = "InsertDate";
                }
                else if (Session["orderNewsAdmin"].Equals(3))
                {
                    strSort = "Author.Name";
                }
                else if (Session["orderNewsAdmin"].Equals(4))
                {
                    strSort = "Department.Name";
                }
            }
            var tempResult = (from content in m_rep.GetAllContent()
                                           where content.Active == true
                                           && content.CategoryID == 1
                                           select content);
            if (strSort == "InsertDate")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting news.
        /// </summary>
        public ActionResult OrderNews(int? id)
        {
            if (id.HasValue)
            {
                Session["orderNewsAdmin"] = id;
            }
            return RedirectToAction("AllNews");
        }

        public ActionResult AllArticles()
        {
            String strSort = "InsertDate";
            IEnumerable<Content> model;

            if (Session["orderArticlesAdmin"] != null)
            {
                if (Session["orderArticlesAdmin"].Equals(1))
                {
                    strSort = "Title";
                }
                else if (Session["orderArticlesAdmin"].Equals(2))
                {
                    strSort = "InsertDate";
                }
                else if (Session["orderArticlesAdmin"].Equals(3))
                {
                    strSort = "Author.Name";
                }
                else if (Session["orderArticlesAdmin"].Equals(4))
                {
                    strSort = "Department.Name";
                }
            }
            var tempResult = (from content in m_rep.GetAllContent()
                              where content.Active == true
                              && content.CategoryID == 2
                              select content);

            if (strSort == "InsertDate")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting Articles.
        /// </summary>
        public ActionResult OrderArticles(int? id)
        {
            if (id.HasValue)
            {
                Session["orderArticlesAdmin"] = id;
            }
            return RedirectToAction("AllArticles");
        }

        public ActionResult AllPapers()
        {
            String strSort = "InsertDate";
            IEnumerable<Content> model;

            if (Session["orderPapersAdmin"] != null)
            {
                if (Session["orderPapersAdmin"].Equals(1))
                {
                    strSort = "Title";
                }
                else if (Session["orderPapersAdmin"].Equals(2))
                {
                    strSort = "InsertDate";
                }
                else if (Session["orderPapersAdmin"].Equals(3))
                {
                    strSort = "Author.Name";
                }
                else if (Session["orderPapersAdmin"].Equals(4))
                {
                    strSort = "Department.Name";
                }
            }
            var tempResult = (from content in m_rep.GetAllContent()
                                           where content.Active == true
                                           && content.CategoryID == 4
                                           select content);

            if (strSort == "InsertDate")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting Papers.
        /// </summary>
        public ActionResult OrderPapers(int? id)
        {
            if (id.HasValue)
            {
                Session["orderPapersAdmin"] = id;
            }
            return RedirectToAction("AllPapers");
        }

        public ActionResult AllResearches()
        {
            String strSort = "InsertDate";
            IEnumerable<Content> model;

            if (Session["orderResearchesAdmin"] != null)
            {
                if (Session["orderResearchesAdmin"].Equals(1))
                {
                    strSort = "Title";
                }
                else if (Session["orderResearchesAdmin"].Equals(2))
                {
                    strSort = "InsertDate";
                }
                else if (Session["orderResearchesAdmin"].Equals(3))
                {
                    strSort = "Author.Name";
                }
                else if (Session["orderResearchesAdmin"].Equals(4))
                {
                    strSort = "Department.Name";
                }
            }
            var tempResult = (from content in m_rep.GetAllContent()
                              where content.Active == true
                              && content.CategoryID == 5
                              select content);

            if (strSort == "InsertDate")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting Researches.
        /// </summary>
        public ActionResult OrderResearches(int? id)
        {
            if (id.HasValue)
            {
                Session["orderResearchesAdmin"] = id;
            }
            return RedirectToAction("AllResearches");
        }

        public ActionResult AllRR()
        {
            String strSort = "InsertDate";
            IEnumerable<Content> model;

            if (Session["orderRRAdmin"] != null)
            {
                if (Session["orderRRAdmin"].Equals(1))
                {
                    strSort = "Title";
                }
                else if (Session["orderRRAdmin"].Equals(2))
                {
                    strSort = "InsertDate";
                }
                else if (Session["orderRRAdmin"].Equals(3))
                {
                    strSort = "Author.Name";
                }
                else if (Session["orderRRAdmin"].Equals(4))
                {
                    strSort = "Department.Name";
                }
            }
            var tempResult = (from content in m_rep.GetAllContent()
                              where content.Active == true
                              && content.CategoryID == 3
                              select content);

            if (strSort == "InsertDate")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting RR.
        /// </summary>
        public ActionResult OrderRR(int? id)
        {
            if (id.HasValue)
            {
                Session["orderRRAdmin"] = id;
            }
            return RedirectToAction("AllRR");
        }
        
        public ActionResult AllEvent()
        {
            String strSort = "StartDate";

            if ( Session["orderEventAdmin"] != null )
            {
                if ( Session["orderEventAdmin"].Equals(1) )
                {
                    strSort = "Name";
                }
                else if ( Session["orderEventAdmin"].Equals(2) )
                {
                    strSort = "StartDate";
                }
                else if ( Session["orderEventAdmin"].Equals(3) )
                {
                    strSort = "EndDate";
                }
                else if (Session["orderEventAdmin"].Equals(4))
                {
                    strSort = "Department.Name";
                }
                else if (Session["orderEventAdmin"].Equals(5))
                {
                    strSort = "Author.Name";
                }
            }
            IEnumerable<Eventss> model = (from content in m_rep.GetAllEvent()
                                          where content.Active == true
                                          select content).AsQueryable().OrderBy(strSort);

            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting Events.
        /// </summary>
        public ActionResult OrderEvent(int? id)
        {
            if (id.HasValue)
            {
                Session["orderEventAdmin"] = id;
            }
            return RedirectToAction("AllEvent");
        }


        [HttpGet]
        public ActionResult CreateEvent()
        {
            return View(new EventViewModel());
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult CreateEvent(EventViewModel model)
        {
            if (ModelState.IsValid)
            {
                Eventss item = new Eventss();
                item.EventID = model.EventID;
                item.Name = model.Name;
                item.StartDate = model.StartDate;
                item.EndDate = model.EndDate;
                item.Description = model.Description;
                item.Active = true;

                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                item.CreatorID = UserID;

                item.DepartmentID = Convert.ToInt32(model.DepartmentID);
                item.AuthorID = Convert.ToInt32(model.AuthorID);
                m_rep.AddEvent(item);
                this.HttpContext.Cache["LatestEvent"] = new CacheUpdate().UpdateCacheEvent();
                return RedirectToAction("AllEvent");
            }
            else
            {
                return View(model);
            }
        }

        [HttpGet]
        public ActionResult EditEvent(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                var model = m_rep.GetEventById(realID);

                if ( model == null )
                {
                    return View("NotFound");
                }

                EventViewModel item = new EventViewModel();
                item.EventID = realID;
                item.Name = model.Name;
                item.StartDate = model.StartDate;
                item.EndDate = model.EndDate;
                item.Description = model.Description;
                item.DepartmentID = model.DepartmentID.ToString();
                item.AuthorID = model.AuthorID.ToString();
                return View(item);
            }
            else
            {
                return View("NotFound");
            }
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult EditEvent(EventViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Eventss item = new Eventss();
                item.EventID = model.EventID;
                item.Name = model.Name;
                item.StartDate = model.StartDate;
                item.EndDate = model.EndDate;
                item.Description = model.Description;
                item.Active = true;

                Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                item.CreatorID = UserID;

                item.DepartmentID = Convert.ToInt32(model.DepartmentID);
                item.AuthorID = Convert.ToInt32(model.AuthorID);
                m_rep.UpdateEvent(item);
                this.HttpContext.Cache["LatestEvent"] = new CacheUpdate().UpdateCacheEvent();
                return RedirectToAction("AllEvent");
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult RemoveEvent(int id)
        {
            var model = (from events in m_rep.GetAllEvent()
                         where events.EventID == id
                         && events.Active == true
                         select events).SingleOrDefault();
            if (model == null)
            {
                return View("NotFound");
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult RemoveEvent(int? id)
        {
            if ( id.HasValue )
            {
                var model = (from events in m_rep.GetAllEvent()
                             where events.EventID == id
                             && events.Active == true
                             select events).SingleOrDefault();
                if ( model == null )
                {
                    return View("NotFound");
                }
                m_rep.DeleteEvent(model);
                this.HttpContext.Cache["LatestEvent"] = new CacheUpdate().UpdateCacheEvent();
                return RedirectToAction("AllEvent");
            }
            else
            {
                return View("NotFound");
            }
        }
 
        public ActionResult AllQA()
        {
            String strSort = "InsertDate";
            IEnumerable<QA> model;

            if (Session["orderQAAdmin"] != null)
            {
                if (Session["orderQAAdmin"].Equals(1))
                {
                    strSort = "Question";
                }
                else if (Session["orderQAAdmin"].Equals(2))
                {
                    strSort = "InsertDate";
                }
                else if (Session["orderQAAdmin"].Equals(3))
                {
                    strSort = "Department.Name";
                }
                else if (Session["orderQAAdmin"].Equals(4))
                {
                    strSort = "CreatorEmail";
                }
                else if (Session["orderQAAdmin"].Equals(5))
                {
                    strSort = "Answered";
                }
            }
            var tempResult = (from item in m_rep.AllQA()
                              where item.Active == true
                              select item);

            if (strSort == "InsertDate")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting QA´s.
        /// </summary>
        public ActionResult OrderQA(int? id)
        {
            if (id.HasValue)
            {
                Session["orderQAAdmin"] = id;
            }
            return RedirectToAction("AllQA");
        }

        [HttpGet]
        public ActionResult EditQA(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                var model = m_rep.GetQAById(realID);

                if ( model == null )
                {
                    return View("NotFound");
                }

                QAAdminViewModel item = new QAAdminViewModel();
                item.QAID = model.QAID;
                item.Question = model.Question;
                item.Answer = model.Answer;
                item.CreatorEmail = model.CreatorEmail;
                item.DepartmentID = model.DepartmentID.ToString();
                return View(item);
            }
            else
            {
                return View("NotFound");
            }
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult EditQA(QAAdminViewModel model)
        {
            if ( ModelState.IsValid )
            {
                QA item = new QA();

                item.QAID = model.QAID;
                item.Question = model.Question;
                item.Answer = model.Answer;
                item.CreatorEmail = model.CreatorEmail;
                item.Active = true;
                if ( item.Answer != null )
                {
                    item.Answered = true;
                    Guid UserID = new Guid(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString());
                    item.AnswerID = UserID;
                }
                item.DepartmentID = Convert.ToInt32(model.DepartmentID);
                m_rep.UpdateQA(item);
                this.HttpContext.Cache["LatestQA"] = new CacheUpdate().UpdateCacheQA();
                return RedirectToAction("AllQA");
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult RemoveQA(int id)
        {
            var model = (from QandA in m_rep.AllQA()
                         where QandA.QAID == id
                         && QandA.Active == true
                         select QandA).SingleOrDefault();
            if ( model == null )
            {
                return View("NotFound");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult RemoveQA(int? id)
        {
            if ( id.HasValue )
            {
                var model = (from QandA in m_rep.AllQA()
                             where QandA.QAID == id
                             && QandA.Active == true
                             select QandA).SingleOrDefault();
                if ( model == null )
                {
                    return View("NotFound");
                }
                m_rep.DeleteQA(model);
                this.HttpContext.Cache["LatestQA"] = new CacheUpdate().UpdateCacheQA();
                return RedirectToAction("AllQA");
            }
            else
            {
                return View("NotFound");
            }
        }
       
        public ActionResult AllLink()
        {
            String strSort = "Url";

            if (Session["orderLinkAdmin"] != null)
            {
                if (Session["orderLinkAdmin"].Equals(1))
                {
                    strSort = "LinkTitle";
                }
                else if (Session["orderLinkAdmin"].Equals(2))
                {
                    strSort = "Url";
                }
            }

            var model = (from item in m_rep.GetAllLink()
                         where item.Active == true
                         select item).AsQueryable().OrderBy(strSort);

            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting Links.
        /// </summary>
        public ActionResult OrderLink(int? id)
        {
            if (id.HasValue)
            {
                Session["orderLinkAdmin"] = id;
            }
            return RedirectToAction("AllLink");
        }

        [HttpGet]
        public ActionResult CreateLink()
        {
            return View(new LinkViewModel());
        }

        [HttpPost]
        public ActionResult CreateLink(LinkViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Link item = new Link();
                item.Url = model.Url;
                item.LinkTitle = model.LinkTitle;
                item.Active = true;
                m_rep.AddLink(item);
                return RedirectToAction("AllLink");
            }
            else
            {
                return View(model);
            }
        }

        [HttpGet]
        public ActionResult EditLink(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                var model = m_rep.GetLinkById(realID);

                if ( model == null )
                {
                    return View("NotFound");
                }

                LinkViewModel item = new LinkViewModel();
                item.LinkID = realID;
                item.LinkTitle = model.LinkTitle;
                item.Url = model.Url;
                return View(item);
            }
            else
            {
                return View("NotFound");
            }
        }

        [HttpPost]
        public ActionResult EditLink(LinkViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Link item = new Link();
                item.LinkID = model.LinkID;
                item.LinkTitle = model.LinkTitle;
                item.Url = model.Url;
                item.Active = true;
                m_rep.UpdateLink(item);
                return RedirectToAction("AllLink");
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult RemoveLink(int id)
        {
            var model = (from links in m_rep.GetAllLink()
                         where links.LinkID == id
                         && links.Active == true
                         select links).SingleOrDefault();
            if ( model == null )
            {
                return View("NotFound");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult RemoveLink(int? id)
        {
            if ( id.HasValue )
            {
                var model = (from links in m_rep.GetAllLink()
                             where links.LinkID == id
                             && links.Active == true
                             select links).SingleOrDefault();
                if ( model == null )
                {
                    return View("NotFound");
                }
                m_rep.DeleteLink(model);
                return RedirectToAction("AllLink");
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult AllAuthor()
        {
            String strSort = "Name";

            if (Session["orderAuthorAdmin"] != null)
            {
                if (Session["orderAuthorAdmin"].Equals(1))
                {
                    strSort = "Name";
                }
                else if (Session["orderAuthorAdmin"].Equals(2))
                {
                    strSort = "Email";
                }
            }
            IEnumerable<Author> model = (from item in m_rep.GetAllAuthors()
                                     where item.Active == true
                                     select item).AsQueryable().OrderBy(strSort);
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting Authors.
        /// </summary>
        public ActionResult OrderAuthor(int? id)
        {
            if (id.HasValue)
            {
                Session["orderAuthorAdmin"] = id;
            }
            return RedirectToAction("AllAuthor");
        }

        [HttpGet]
        public ActionResult CreateAuthor()
        {
            return View(new AuthorViewModel());
        }

        [HttpPost]
        public ActionResult CreateAuthor(AuthorViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Author item = new Author();
                item.AuthorID = model.AuthorID;
                item.Name = model.Name;
                item.Email = model.Email;
                item.Active = true;
                m_rep.AddAuthor(item);
                return RedirectToAction("AllAuthor");
            }
            else
            {
                return View(model);
            }
        }

        [HttpGet]
        public ActionResult EditAuthor(int? id)
        {
            if ( id.HasValue )
            {
                int realID = id.Value;
                var model = m_rep.GetAuthorById(realID);

                if ( model == null )
                {
                    return View("NotFound");
                }

                AuthorViewModel item = new AuthorViewModel();
                item.AuthorID = realID;
                item.Name = model.Name;
                item.Email = model.Email;
                return View(item);
            }
            else
            {
                return View("NotFound");
            }
        }

        [HttpPost]
        public ActionResult EditAuthor(AuthorViewModel model)
        {
            if ( ModelState.IsValid )
            {
                Author item = new Author();
                item.AuthorID = model.AuthorID;
                item.Name = model.Name;
                item.Email = model.Email;
                item.Active = true;
                m_rep.UpdateAuthor(item);
                return RedirectToAction("AllAuthor");
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult RemoveAuthor(int id)
        {
            var model = (from author in m_rep.GetAllAuthors()
                         where author.AuthorID == id
                         && author.Active == true
                         select author).SingleOrDefault();
            if ( model == null )
            {
                return View("NotFound");
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult RemoveAuthor(int? id)
        {
            if ( id.HasValue )
            {
                var model = (from author in m_rep.GetAllAuthors()
                             where author.AuthorID == id
                             && author.Active == true
                             select author).SingleOrDefault();
                if ( model == null )
                {
                    return View("NotFound");
                }
                m_rep.DeleteAuthor(model);
                return RedirectToAction("AllAuthor");
            }
            else
            {
                return View("NotFound");
            }
        }

        public ActionResult AllUser()
        {
            String strSort = "aspnet_User.UserName";
            IEnumerable<aspnet_Membership> model;

            if (Session["orderUserAdmin"] != null)
            {
                if (Session["orderUserAdmin"].Equals(1))
                {
                    strSort = "aspnet_User.UserName";
                }
                else if (Session["orderUserAdmin"].Equals(2))
                {
                    strSort = "Email";
                }
                else if (Session["orderUserAdmin"].Equals(3))
                {
                    strSort = "CreateDate";
                }
            }

            var tempResult = (from content in m_rep.AllUsers()
                              select content);

            if (strSort == "CreateDate")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helpers function for sorting Users.
        /// </summary>
        public ActionResult OrderUser(int? id)
        {
            if (id.HasValue)
            {
                Session["orderUserAdmin"] = id;
            }
            return RedirectToAction("AllUser");
        }

        /// <summary>
        /// Function gets the role for a specified user for editing and renders it.
        /// </summary>
        public ActionResult EditUserRole(string id)
        {
            if ( id != null )
            {
                //string realID = id.Value;
                var model = m_rep.GetUserById(id);

                if ( model == null )
                {
                    return View("NotFound");
                }
                UserViewModel item = new UserViewModel();

                item.UserName = model.UserName;

                var temprole = (from role in m_rep.AllRoles()
                                where role.UserId == model.UserId
                                select role.aspnet_Role.RoleName).SingleOrDefault();
                if (temprole == null)
                {
                    item.RoleName = "None";
                    item.OldRole = item.RoleName;
                }
                else
                {
                    item.OldRole = temprole;
                    item.RoleName = temprole;
                }
                return View(item);
            }
            else
            {
                return View("NotFound");
            }
        }

        /// <summary>
        /// Function Add, removes or changes the roles for a user
        /// </summary>
        [HttpPost]
        public ActionResult EditUserRole(UserViewModel model)
        {
            if ( ModelState.IsValid )
            {
                if (model.OldRole == "None" && model.RoleName != "None")
                {
                    Roles.AddUserToRole(model.UserName, model.RoleName);               
                }
                else if (model.OldRole != "None" && model.RoleName == "None")
                {
                    Roles.RemoveUserFromRole(model.UserName, model.OldRole);
                }
                else if (model.OldRole != "None" && model.OldRole != model.RoleName)
                {
                    Roles.RemoveUserFromRole(model.UserName, model.OldRole);
                    Roles.AddUserToRole(model.UserName, model.RoleName);
                }
                return RedirectToAction("AllUser");
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult AllChild()
        {
            String strSort = "Name";
            IEnumerable<Child> model;

            if (Session["orderChildAdmin"] != null)
            {
                if (Session["orderChildAdmin"].Equals(1))
                {
                    strSort = "Name";
                }
                else if (Session["orderChildAdmin"].Equals(2))
                {
                    strSort = "aspnet_Membership.aspnet_User.UserName";
                }
                else if (Session["orderChildAdmin"].Equals(3))
                {
                    strSort = "Created";
                }
                else if (Session["orderChildAdmin"].Equals(4))
                {
                    strSort = "ProfilePassword";
                }
            }
            var tempResult = (from item in m_rep.AllChilds()
                              where item.Active == true
                              select item);

            if (strSort == "Created")
            {
                model = tempResult.AsQueryable().OrderByDescending(strSort);
            }
            else
            {
                model = tempResult.AsQueryable().OrderBy(strSort);
            }
            return View(model);
        }

        /// <summary>
        /// Helper functino for sorting Children
        /// </summary>
        public ActionResult OrderChild(int? id)
        {
            if (id.HasValue)
            {
                Session["orderChildAdmin"] = id;
            }
            return RedirectToAction("AllChild");
        }

        public ActionResult RemoveChild(int id)
        {
            var model = (from child in m_rep.AllChilds()
                         where child.ChildID == id
                         && child.Active == true
                         select child).SingleOrDefault();
            if ( model == null )
            {
                return View("NotFound");
            }
            return View(model);
        }


        [HttpPost]
        public ActionResult RemoveChild(int? id)
        {
            if ( id.HasValue )
            {
                var model = (from child in m_rep.AllChilds()
                             where child.ChildID == id
                             && child.Active == true
                             select child).SingleOrDefault();
                if ( model == null )
                {
                    return View("NotFound");
                }
                m_rep.DeleteChild(model);
                return RedirectToAction("AllChild");
            }
            else
            {
                return View("NotFound");
            }
        }
    }
}
